package com.example.ssmp.contorller;


import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ssmp.bean.Book;
import com.example.ssmp.contorller.utils.R;
import com.example.ssmp.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;


@RestController
@RequestMapping("/books")
public class BookContorller {

    @Autowired
    IBookService bookService;
    @GetMapping
   public R getAll() {
        return new R(true,bookService.list());
    }

    @PostMapping
    public R saveBook(@RequestBody Book book)  {
        boolean flag = bookService.saveBook(book);
        return new R(flag,flag ? "保存成功^_^" : "报存失败-_-!");
    }

    @PutMapping
    public R updateBook(@RequestBody Book book){
        boolean flag = bookService.updateById(book);
        return new R(flag,flag ? "修改成功^_^" : "修改失败-_-!");
    }


    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id){
        return new R(true,bookService.getById(id));
    }

    @DeleteMapping({"/{id}"})
    public  R delete( @PathVariable("id") Integer id){
        boolean flag = bookService.delete(id);
        return  new R(flag,flag ? "删除成功^_^" : "删除失败-_-!");
    }


//    @GetMapping("{current}/{size}")
//    public R getPage(@PathVariable int current,@PathVariable int size){
//
//        Page<Book> page = bookService.getPage(current, size);
//        if (current> page.getPages())
//           page = bookService.getPage((int) page.getPages(), size);
//        return new R(true,page);
//
//    }


    @GetMapping("{current}/{size}")
    public R getPage(@PathVariable int current,@PathVariable int size,Book book){

        System.out.println("book:"+book);

        Page<Book> page = bookService.getPage(current, size, book);
        if (current> page.getPages())
            page = bookService.getPage((int) page.getPages(), size,book);
        return new R(true,page);

    }
}
